﻿using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ServerData 
{
    public int id;
    public string ip;
    public string name;
    public int areaid;
    public int channelID;
    public int isOpen;
    public bool isNew;
}

public class AreaData
{
    public int AreaId;
    public string Name;
}

public class ServerMgr : Singleton<ServerMgr>, IBaseData
{
    public List<ServerData> mServerList = new List<ServerData>();
    public Dictionary<int, AreaData> mDicArea = new Dictionary<int, AreaData>();
    public Dictionary<int, Dictionary<int, List<ServerData>>> mDicAreaServer;

    public ServerData curSd;
    public int curPlatform;

    public ServerMgr()
    {
        mDicAreaServer = new Dictionary<int, Dictionary<int, List<ServerData>>>();
        curSd = new ServerData(); Init();
    }

    public void Init()
    {
        mServerList.Clear();
        mDicArea.Clear();
    }

    public List<AreaData> GetAreaList()
    {
        return mDicArea.Values.ToList();
    }

    public List<ServerData> GetServerList(int AreaId)
    {
        if (mDicAreaServer.ContainsKey(curPlatform))
        {
            if (mDicAreaServer[curPlatform].ContainsKey(AreaId))
            {
                List<ServerData> sDataList = new List<ServerData>();
                for (int i = 0; i < mDicAreaServer[curPlatform][AreaId].Count; i++)
                {
                    if (mDicAreaServer[curPlatform][AreaId][i].isOpen == 1)
                    {
                        sDataList.Add(mDicAreaServer[curPlatform][AreaId][i]);
                    }
                }
                return sDataList;
            }
        }
        return null;
    }

    public void SetServerIp(int Id)
    {
        for (int i = 0; i < mServerList.Count; i++)
        {
            if (mServerList[i].id == Id)
            {
                curSd = mServerList[i];
                break;
            }
        }
    }

    public string GetCurServerIP()
    {
        return curSd.ip;
    }

    public void SaveLastServer()
    {
        PlayerPrefs.SetString("lastserver", curSd.ip);
    }
    
    public string GetLastServer()
    {
        return PlayerPrefs.GetString("lastserver", ""); 
    }

    public ServerData GetNewestSD()
    {
        // 如果没有返回最新的
        int id = 0;
        foreach (var item in mDicArea)
        {
            if (item.Key > id)
            {
                id = item.Key;
            }
        }

        if (mDicAreaServer.ContainsKey(curPlatform) && mDicAreaServer[curPlatform] != null)
        {
            if (mDicAreaServer[curPlatform].ContainsKey(id) && mDicAreaServer[curPlatform][id] != null)
            {
                mDicAreaServer[curPlatform][id][mDicAreaServer[curPlatform][id].Count - 1].isNew = true;
                return mDicAreaServer[curPlatform][id][mDicAreaServer[curPlatform][id].Count - 1];
            }
        }
        return null;
    }

    public void InitCurSd(Dictionary<int, AreaData> realDic)
    {
        foreach (var area in realDic)
        {
            List<ServerData> sList = GetServerList(area.Key);
            if (sList != null && sList.Count > 0)
            {
                mDicArea.Add(area.Key, area.Value);
            }
        }

        GetNewestSD(); bool bExist = false;
        string lastip = GetLastServer();
        
        if (lastip == "")
        {
            curSd = GetNewestSD();
        }
        else
        {
            for (int i = 0; i < mServerList.Count; i++)
            {
                if (mServerList[i].ip == lastip)
                {
                    bExist = true;
                    if (mServerList[i].isOpen == 1)
                    {
                        curSd = mServerList[i];
                    }
                    else
                    {
                        curSd = GetNewestSD();
                    }
                    break;
                }
            }
        }

        if (!bExist)
        {
            curSd = GetNewestSD();
        }
    }

    public string GetNowServerName()
    {
        if (curSd != null)
        {
            return curSd.id + " " + curSd.name;
        }
        return "";
    }

    public void GetListJson()
    {
        // 没有选区信息，才去请求
        if (mServerList.Count <= 0)
        {
            // 没有连接先连接
            if (!WebClient.GetSingleton().Connected)
            {
                WebClient.GetSingleton().ConnectWeb();
            }
        }
        else
        {
            ZEventCenter.DispatchEvent(new ZEvent(ConstData.GET_SERVERLIST_OK));
        }
    }

    public void FillServerList(string svrList)
    {
        mServerList.Clear();
        mDicArea.Clear();
        mDicAreaServer.Clear();

        JObject arrayObj = JObject.Parse(svrList);
        IEnumerable<JProperty> properties = arrayObj.Properties();
        Dictionary<int, AreaData> realDic = new Dictionary<int, AreaData>();
        foreach (var item in properties)
        {
            if (item.Name == "Wsl")
            {
                JArray array = item.Value as JArray;
                for (int i = 0; i < array.Count; ++i)
                {
                    ServerData sData = new ServerData();
                    JObject token = array[i] as JObject;
                    sData.id = token.Value<int>("ID");
                    sData.ip = token.Value<string>("IP");
                    sData.name = token.Value<string>("名称");
                    sData.areaid = token.Value<int>("所属区");
                    sData.channelID = token.Value<int>("渠道");
                    sData.isOpen = token.Value<int>("是否开启");
                    mServerList.Add(sData);

                    if (mDicAreaServer.ContainsKey(sData.channelID))
                    {
                        if (mDicAreaServer[sData.channelID].ContainsKey(sData.areaid))
                        {
                            mDicAreaServer[sData.channelID][sData.areaid].Add(sData);
                        }
                        else
                        {
                            List<ServerData> nowList = new List<ServerData>();
                            nowList.Add(sData);
                            mDicAreaServer[sData.channelID].Add(sData.areaid, nowList);
                        }
                    }
                    else
                    {
                        Dictionary<int, List<ServerData>> nowDic = new Dictionary<int, List<ServerData>>();
                        List<ServerData> s = new List<ServerData>();
                        s.Add(sData);
                        nowDic.Add(sData.areaid, s);
                        mDicAreaServer.Add(sData.channelID, nowDic);
                    }
                }
            }
            else if (item.Name == "Wal")
            {
                JArray array = item.Value as JArray;
                for (int i = 0; i < array.Count; ++i)
                {
                    AreaData aData = new AreaData();
                    JObject token = array[i] as JObject;
                    int id = token.Value<int>("ID");

                    aData.AreaId = id;
                    aData.Name = token.Value<string>("名称");
                    if (!realDic.ContainsKey(id))
                    {
                        realDic.Add(id, aData);
                    }
                }
            }
        }
        InitCurSd(realDic);
    }
}